package com.mspbots.cw.trigger;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mspbots.api.client.CoreClient;
import com.mspbots.cw.amqp.model.TimeEntry;
import com.mspbots.cw.amqp.model.TriggerEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Map;

import static com.mspbots.common.TriggerEvent.CW_TIMEENTRY_NEW;


/**
 * @author Harry hou
 * @date 2019/11/22 15:17
 */

@Log4j2
@Service
@RequiredArgsConstructor
public class TimeEntryTriggerEvent {

    @Autowired
    private AmqpTemplate amqpTemplate;
    private final ObjectMapper objectMapper;
    private final CoreClient coreClient;

    //default ms
    static Integer times = 60 * 1000;

    private static MessagePostProcessor processor = message -> {
        message.getMessageProperties().setDelay(times);
        return message;
    };

    @RabbitListener(queues = "trigger.intforward")
    public void publishTimeEntryTriggerEvent(TimeEntry tenantTimeEntryDTO) {
        try {
            if(ObjectUtils.isEmpty(tenantTimeEntryDTO.getEnteredDate())){
                return;
            }
            if (LocalDateTime.now().minusHours(24).isBefore(tenantTimeEntryDTO.getEnteredDate())) {
                    Map<String, Object> params = Map.of(
                            "tenantId", tenantTimeEntryDTO.getTenantId(),
                            "cwUid", tenantTimeEntryDTO.getCwUid()
                    );
                    JsonNode userMapping = coreClient.get("/user-mapping/detail", params).block();
                    if (!ObjectUtils.isEmpty(userMapping)) {
                        log.debug("time entry trigger {} ",tenantTimeEntryDTO.getExtend().get("id").asText());
                        JsonNode extend = tenantTimeEntryDTO.getExtend();
                        ObjectNode payload = (ObjectNode) extend;
                        payload.put("action",tenantTimeEntryDTO.getAction());
                        TriggerEvent triggerEvent = new TriggerEvent();
                        triggerEvent.setTenantId(tenantTimeEntryDTO.getTenantId());
                        triggerEvent.setEventName(CW_TIMEENTRY_NEW.getEvent());
                        triggerEvent.setScope(CW_TIMEENTRY_NEW.getScope());
                        triggerEvent.setPayload(payload);
                        triggerEvent.setUserInfo(userMapping);

                        /*if (!StringUtils.isEmpty(userMapping.get("userId")) && "new".equalsIgnoreCase(tenantTimeEntryDTO.getAction())) {
                            Map<String,Object> scriptListParams = Map.of(
                                    "scope", CW_TIMEENTRY_NEW.getScope(),
                                    "eventName",CW_TIMEENTRY_NEW.getEvent(),
                                    "tenantId", tenantTimeEntryDTO.getTenantId(),
                                    "enable", true);
                            coreClient.getFlux("/script/list", scriptListParams)
                                    .doOnNext(item -> {
                                        Map<String, Object> param = Map.of("scriptId",item.get("systemScriptId"),
                                                "tenantUserId", userMapping.get("tenantUserId"),
                                                "userId",userMapping.get("userId"),
                                                "tenantId", tenantTimeEntryDTO.getTenantId());
                                        coreClient.post("/teams/messages/cache-bot",param).subscribe();
                                    }).subscribe();
                        } else {
                            log.error("time entry cache error: no userId for tenantUserId [{}]", userMapping.get("tenantUserId"));
                        }*/

                        this.amqpTemplate.convertAndSend("msp.trigger.event", "", triggerEvent);
                        log.debug("cw msp.trigger.event NewTimeEntry{} ", this.objectMapper.convertValue(triggerEvent,JsonNode.class));
                    } else {
                        log.error("cw user [{}] has no mapping [{}]", tenantTimeEntryDTO.getCwUid(), tenantTimeEntryDTO.getCwTid());
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
